package ai.plantdata.dao.util;

import ai.plantdata.config.RDBTemplateFactory;
import ai.plantdata.constant.DbTypeEnum;
import ai.plantdata.vo.DataSourceConfig;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Author: WangHui
 * @Date: 2021/7/16 17:24
 * @Description:
 */
public class JdbcUtils {

    public static Connection getConnection(DataSourceConfig dataSourceConfig) {
        try {
            DbTypeEnum from = DbTypeEnum.from(dataSourceConfig.getType());
            DataSource source = RDBTemplateFactory.factory(dataSourceConfig, from);
            return source.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException("关系型数据库连接失败");
        }
    }

    public static void close(PreparedStatement ps, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
